package com.yxt.ui;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.yxt.common.sys.CommConstant;
import com.yxt.common.ui.ActivityStackControlUtil;
import com.yxt.common.ui.NormalTableAdapter;
import com.yxt.common.ui.NormalTableAdapter.TableCell;
import com.yxt.common.ui.NormalTableAdapter.TableRow;
import com.yxt.common.widget.ListWheelAdapter;
import com.yxt.common.widget.OnWheelChangedListener;
import com.yxt.common.widget.WheelView;
import com.yxt.exception.InternetException;
import com.yxt.exception.RemoteServerException;
import com.yxt.exception.XmlParserException;
import com.yxt.model.Address;
import com.yxt.service.AddressService;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

public class AddressListActivity extends Activity {
	private static final int MENU_SEARCH = Menu.FIRST+1;
	private static final int MENU_ALL = Menu.FIRST+2;
	private static final int MENU_DOWNLOAD = Menu.FIRST + 3;
	private static final int height = 40;
	private static final int color = Color.WHITE;
	
	private AddressService service = new AddressService(AddressListActivity.this);
	private List<String> provinces = new ArrayList<String>();
	private List<String> depts = new ArrayList<String>();
	private ProgressDialog dialog;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
		setContentView(R.layout.address_list);   //软件activity的布局	
		ActivityStackControlUtil.add(this); 
		Button btnBackHome = (Button)findViewById(R.id.btnBackHome);
		btnBackHome.setOnClickListener(new OnClickListener(){
			public void onClick(View arg0) {
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), MainActivity.class);
				startActivity(intent);
			}
		});
		initComponent();
	}
	
	private void downloadAddressList() {
		try {
			InputStream inputStream = getInputStream();
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
			parser.parse(inputStream, new AddressListHandler());
		} catch (IOException e) {
			dialog.cancel();
			throw new InternetException("");
		} catch (ParserConfigurationException e){
			dialog.cancel();
			throw new XmlParserException("");
		} catch(SAXException ex) {
			dialog.cancel();
			throw new XmlParserException("");
		}		
	}

	private InputStream getInputStream() throws IOException{
		Intent intent = getIntent();
		String itemId = intent.getStringExtra("itemId");
		Map<String, String> menu = CommConstant.Main.FUNCTIONS.get(CommConstant.Main.CURRENT_TEMPLATE_CODE).get(itemId);
		String server = menu.get("server");
		InputStream input = null;
		if (CommConstant.DEBUG_MODEL) {
			input = new FileInputStream(CommConstant.Config.DEFAULT_PHONE_DIR + CommConstant.Config.XML_LOCATION + "contract.xml");
		} else {
			URL url = new URL(server + "Contacts/Download.aspx?iphoneid=" + CommConstant.Main.CURRENT_IPHONE_CODE + "&version=" + CommConstant.Main.CURRENT_IPHONE_VERSION + "&areacode=" + CommConstant.Main.CURRENT_AREA_CODE + "&rvnm="+CommConstant.Main.CURRENT_RIVER_CODE);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(CommConstant.Config.DEFAULT_TIMEOUT);
			conn.connect();
			input = conn.getInputStream();
		}
		return input;
	}
	
	private class AddressListHandler extends DefaultHandler {
		
		public void endDocument() throws SAXException {
			super.endDocument();
		}

		public void startDocument() throws SAXException {
			super.startDocument();
			service.deleteAddress();
		}

		public void startElement(String uri, String localName, String qName,
				Attributes attrs) throws SAXException {			
			if ("info".equals(localName)) {
				Address addr = new Address();
				addr.setId(attrs.getValue("id"));
				addr.setStb_pcode(attrs.getValue("stb_pcode"));
				addr.setDepartmentid(attrs.getValue("departmentid"));
				addr.setName(attrs.getValue("name"));
				addr.setJob(attrs.getValue("job"));
				addr.setOfficetel(attrs.getValue("officetel"));
				addr.setHometel(attrs.getValue("hometel"));
				addr.setMobiltel(attrs.getValue("mobiltel"));
				addr.setSfjob(attrs.getValue("sfjob"));
				addr.setPinyin(attrs.getValue("ename"));
				addr.setPersonorder(attrs.getValue("unit"));
				addr.setOrderid(attrs.getValue("orderby"));
				service.saveAddress(addr);
			}else if ("message".equals(localName)) {
				throw new RemoteServerException(attrs.getValue("info"));
			}
		}
	}
	
	private void initComponent(){
		provinces.clear();
		depts.clear();
		provinces.add(CommConstant.Config.DEFAULT_NAME);
		provinces.addAll(service.getEnumProvinces());
		depts.add(CommConstant.Config.DEFAULT_NAME);
		//填充LISTVIEW
        List<Address> contracts = service.getAddressList("","");
		fillAddressList(contracts);
	}
	
	private void fillAddressList(List<Address> contracts){
		ArrayList<TableRow> table = new ArrayList<TableRow>();     
        int[] width = {250};
        Map<String,String> map = new HashMap<String,String>();
        int count = contracts.size();
        for (int i = 0; i < count; i++) {
        	Address addr = contracts.get(i);
        	String city = addr.getStb_pcode();
        	if (!map.containsKey(city)) {
        		TableCell[] cells = new TableCell[1];
                cells[0] = new TableCell(city, LayoutParams.FILL_PARENT, 40, Color.GRAY, TableCell.DISABLE);  
                table.add(new TableRow(cells)); 
        		map.put(city, city); 
        	}
        	TableCell[] cells = new TableCell[1];
        	cells[0] = new TableCell("  " + addr.getName()+ "■" + addr.getJob(), width[0], height, color, TableCell.STRING, new TextItemOnClickListener(addr.getId())); 
        	table.add(new TableRow(cells));  
        }
        NormalTableAdapter tableAdapter = new NormalTableAdapter(this, table);   
        ListView lstWaterStation = (ListView)findViewById(R.id.lstAddressList);
        lstWaterStation.setAdapter(tableAdapter);
		
		TextView lblTitle = (TextView)findViewById(R.id.lblTitle);
		lblTitle.setText("通讯录(" + String.valueOf(count) + ")");
	}
	
	/**
	 * 创建底部菜单
	 * */
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, MENU_SEARCH, 1, R.string.menu_addr_search);
		menu.add(0, MENU_ALL, 3, R.string.menu_all);
		menu.add(0, MENU_DOWNLOAD, 4, R.string.menu_download);
		return super.onCreateOptionsMenu(menu);
	}
	
	/**
	 * 点击底部菜单项时的处理
	 */
	public boolean onOptionsItemSelected(MenuItem item) {	
		Intent intent = new Intent();	
		switch (item.getItemId()) {
			case MENU_SEARCH:
				intent.setClass(getApplicationContext(), AddressSearchActivity.class);
				startActivity(intent);
				return true;
			case MENU_ALL:
				View view = View.inflate(AddressListActivity.this, R.layout.comm_addr, null);
				final AlertDialog menuDialog = new AlertDialog.Builder(AddressListActivity.this).create();
				menuDialog.setView(view);
				menuDialog.show();
				final WheelView wheelProvince = (WheelView)view.findViewById(R.id.wheelProvince);
				wheelProvince.setAdapter(new ListWheelAdapter<String>(provinces,CommConstant.Config.ADDR_MAXLENGTH));
				final WheelView wheelDepartment = (WheelView)view.findViewById(R.id.wheelDepartment);
				wheelDepartment.setAdapter(new ListWheelAdapter<String>(depts,CommConstant.Config.ADDR_MAXLENGTH));
				//添加滚动事件
				wheelProvince.addChangingListener(new OnWheelChangedListener(){
					public void onChanged(WheelView wheel, int oldValue, int newValue) {
						depts.clear();
						depts.add(CommConstant.Config.DEFAULT_NAME);
						depts.addAll(service.getEnumDepartmentByProvince(provinces.get(wheelProvince.getCurrentItem())));
						wheelDepartment.setAdapter(new ListWheelAdapter<String>(depts,CommConstant.Config.ADDR_MAXLENGTH));
					}
				});
				//添加按钮事件
				Button btnConfirm = (Button)view.findViewById(R.id.btnConfirm);
				Button btnCancel = (Button)view.findViewById(R.id.btnCancel);				
				btnConfirm.setOnClickListener(new OnClickListener(){
					public void onClick(View v) {
						String pcode = ""; 
						String dcode = ""; 
						if (wheelProvince.getCurrentItem() > 0) {
							pcode = provinces.get(wheelProvince.getCurrentItem());
						}
						if (wheelDepartment.getCurrentItem() > 0) {
							dcode = depts.get(wheelDepartment.getCurrentItem());
						}
						menuDialog.cancel();
						fillAddressList(service.getAddressList(pcode, dcode));
					}			
				});
				btnCancel.setOnClickListener(new OnClickListener(){
					public void onClick(View v) {
						menuDialog.cancel();
					}			
				});
				return true;
			case MENU_DOWNLOAD:	
				dialog = new ProgressDialog(this);
				dialog.setTitle("通讯录");
				dialog.setMessage("数据下载中,请稍候...");
				dialog.show();
				final Handler hanlder = new Handler(){
					public void handleMessage(Message msg)	{
						if (msg.what == 1)	{
							initComponent();
						}
					}
				};
				
				new Thread(){
					public void run(){
						Looper.prepare();
						downloadAddressList();
						Message m = new Message();
						m.what = 1;
						hanlder.sendMessage(m);	// 给handle发送的消息
						Looper.loop();
					};

				}.start();
				return true;
		}
		return super.onOptionsItemSelected(item);
	}

	private class TextItemOnClickListener implements OnClickListener{
		private String addrId;
		public TextItemOnClickListener(String addrId){	
			this.addrId = addrId;
		}
		
		public void onClick(View v) {
			Intent intent = new Intent();
			intent.setClass(getApplicationContext(), AddressDetailActivity.class);
			intent.putExtra("addrId", addrId);
			startActivity(intent);
		}
	}

	protected void onDestroy() {
		super.onDestroy();
		service.closeDB();
        ActivityStackControlUtil.remove(this);
	}
}